"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : 口令复杂度检查
Create At   : 2022/3/11
Owner       : opentestcase012
Description :
    1.设置参数并重启数据库enableSeparationOfDuty=on
    gs_guc set -N all -I all -c enableSeparationOfDuty=on;
    gs_om -t restart
    2.创建用户
    drop user if exists u_authen_password_0002 cascade;
    create user u_authen_password_0002 identified by 'test@123';
    3.修改密码分别为：用户名,连续字符/数字,长度小于8个字符,全部为大写字母/小写字母/数字/特殊字符
    alter user "u_authen_password_0002" identified by '[新密码]' replace '[旧密码]';
    4.清理环境
    drop user if exists u_authen_password_0002 cascade;
    gs_guc reload -N all -I all -c authentication_timeout=[默认参数值]
    gs_guc set -N all -I all -c authentication_timeout=[默认参数值];
    gs_om -t restart
Expect      :
    1.成功
    2.成功
    3.修改失败,要求最少包含3种类型字符,长度最少8位,不能和表同名
    4.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common()
        self.u_name = 'u_security_authen_password_0002'
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')
        self.default_value2 = self.common.show_param('authentication_timeout')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=on; ' \
               'expect:成功-----'
        self.log.info(text)
        mod_msg = self.pri_sh.execute_gsguc('set',
                                            self.constant.GSGUC_SUCCESS_MSG,
                                            'enableSeparationOfDuty=on')
        self.assertTrue(mod_msg, '执行失败:' + text)
        result = self.pri_sh.restart_db_cluster()
        self.assertTrue(result, '执行失败' + text)

        text = '-----step2：创建新用户 expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop user if exists {self.u_name} cascade; " \
            f"create user {self.u_name} " \
            f"identified by '{macro.GAUSSDB_INIT_USER_PASSWD}';"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)

        text = '-----step3：修改密码分别为：用户名,连续字符/数字,长度小于8个字符,全部为大写字母' \
               '/小写字母/数字/特殊字符 expect:修改失败,要求最少包含3种类型字符,长度最少8位,不能和表同名-----'
        self.log.info(text)
        passwords = [f'{self.u_name}', '987654321', 'abcdefghi',
                     'abc123', 'AZCWEHGWRT', 'azcwehgwrt', '365489654',
                     '*$%&*&^%^']
        for pw in passwords:
            sql_cmd = f"alter user {self.u_name} identified by '{pw}' " \
                f"replace '{macro.GAUSSDB_INIT_USER_PASSWD}';"
            res = self.pri_sh.execut_db_sql(sql_cmd)
            self.log.info(res)
            if pw == self.u_name:
                self.assertIn('Password should not equal to the rolname',
                              res, '执行失败:' + text)
            elif pw == 'abc123':
                self.assertIn('Password must contain at least 8 characters',
                              res, '执行失败:' + text)
            else:
                self.assertIn('Password must contain at least three '
                              'kinds of characters', res, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step4：清理环境-----')
        text1 = '-----删除用户 expect:成功-----'
        self.log.info(text1)
        drop_cmd = f"drop user if exists {self.u_name} cascade;"
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)

        text2 = '-----恢复参数enableSeparationOfDuty并重启数据库 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_msg,
                      '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
